When a cookie is protected with the secure
attribute set to true it will not be send by the browser over an unencrypted HTTP
request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack.
Ask Yourself Whether
- the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication.
- it’s not sure that the website contains mixed content or not
(ie HTTPS everywhere or not)
There is a risk if you answered yes to any of those questions.
Recommended Secure Coding Practices
- It is recommended to use
HTTPs
everywhere so setting the secure
flag to true should be the default behaviour
when creating cookies.
- Set the
secure
flag to true for session-cookies.
Sensitive Code Example
For Go Standard Library:
import "net/http"
func handler(w http.ResponseWriter, req *http.Request) {
cookie := http.Cookie{}
cookie.Name = "cookiename"
cookie.Value = "cookievalue"
http.SetCookie(w, &cookie) // Sensitive: Secure is false by default
}
For Beego:
import "github.com/beego/beego/v2/server/web"
func (ctrl *MainController) handler() {
ctrl.Ctx.SetCookie("name1", "value1", 200, "/", "example.com", false, false) // Sensitive
}
For Fiber:
import "github.com/gofiber/fiber/v2"
func handler(c *fiber.Ctx) error {
cookie := new(fiber.Cookie)
cookie.Name = "name"
cookie.Value = "value"
c.Cookie(cookie) // Sensitive: Secure is false by default
return c.SendString("")
}
For Gin:
import "github.com/gin-gonic/gin"
func handler(c *gin.Context) {
c.SetCookie("name", "value", 200, "/", "example.com", false, false) // Sensitive
c.JSON(http.StatusOK, gin.H{"message": ""})
}
Compliant Solution
For Go Standard Library:
import "net/http"
func handler(w http.ResponseWriter, req *http.Request) {
cookie := http.Cookie{}
cookie.Name = "cookiename"
cookie.Value = "cookievalue"
cookie.Secure = true
http.SetCookie(w, &cookie)
}
For Beego:
import "github.com/beego/beego/v2/server/web"
func (ctrl *MainController) handler() {
ctrl.Ctx.SetCookie("name1", "value1", 200, "/", "example.com", true, false)
}
For Fiber:
import "github.com/gofiber/fiber/v2"
func handler(c *fiber.Ctx) error {
cookie := new(fiber.Cookie)
cookie.Name = "name"
cookie.Value = "value"
cookie.Secure = true
c.Cookie(cookie)
return c.SendString("")
}
For Gin:
import "github.com/gin-gonic/gin"
func handler(c *gin.Context) {
c.SetCookie("name", "value", 200, "/", "example.com", true, false)
c.JSON(http.StatusOK, gin.H{"message": ""})
}
See